package com.jhuster.jnote;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;

//import butterknife.ButterKnife;
//import butterknife.Bind;

import android.content.SharedPreferences;


public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final int REQUEST_SIGNUP = 0;


    //@Bind(R.id.input_email) EditText _emailText;
    //@Bind(R.id.input_password) EditText _passwordText;
    //@Bind(R.id.btn_login) Button _loginButton;
    //@Bind(R.id.link_signup) TextView _signupLink;

    //private TextView formula=(TextView) findViewById((R.id.formula_area));
    private EditText _emailText;
    private EditText _passwordText;
    private Button _loginButton;
    private TextView _signupLink;

    private TextView _changepasswordLink;



    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //ButterKnife.bind(this);


        _emailText=(EditText) findViewById(R.id.input_email);
        _passwordText=(EditText) findViewById(R.id.input_password);
        _loginButton=(Button) findViewById(R.id.btn_login);
        _signupLink=(TextView) findViewById(R.id.link_signup);
        _changepasswordLink=(TextView) findViewById(R.id.link_change_password);



        //获取preferences和editor对象
        preferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        editor = preferences.edit();

        /*
        启动程序时首先检查sharedPreferences中是否储存有用户名和密码
        若无，则将checkbox状态显示为未选中
        若有，则直接中sharedPreferences中读取用户名和密码，并将checkbox状态显示为已选中
        这里getString()方法需要两个参数，第一个是键，第二个是值。
        启动程序时我们传入需要读取的键，值填null即可。若有值则会自动显示，没有则为空。
        */
        String name = preferences.getString("email",null);
        String password = preferences.getString("password", null);
        if (name == null||password == null) {
            //checkBox.setChecked(false);
            _emailText.setText(name);
            _passwordText.setText(password);
        } else {
            _emailText.setText(name);
            _passwordText.setText(password);
            login();
        }






        _loginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    // 进行点击事件后的逻辑操作
                    login();
                }

            }
        });

        _signupLink.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Start the Signup activity
                Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
                startActivityForResult(intent, REQUEST_SIGNUP);
                //finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });

        _changepasswordLink.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Start the ChangePassword activity
                Intent intent = new Intent(getApplicationContext(), ChangePasswordActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });





    }

    public void login() {
        Log.d(TAG, "Login");

        if (!validate()) {
            editor.remove("email");
            editor.remove("password");
            editor.commit();
            onLoginFailed();
            return;
        }

        String email = _emailText.getText().toString();
        String password = _passwordText.getText().toString();

        editor.putString("email", email);
        //editor.commit();
        editor.putString("password", password);
        editor.commit();




        _loginButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this, R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Authenticating...");
        progressDialog.show();



        // TODO: Implement your own authentication logic here.

        new android.os.Handler().postDelayed(    //延迟跳转
                new Runnable() {
                    public void run() {
                        // On complete call either onLoginSuccess or onLoginFailed
                        onLoginSuccess();
                        // onLoginFailed();
                        progressDialog.dismiss();
                    }
                }, 3000);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   //用于处理跳转到的注册界面的返回值
        if (requestCode == REQUEST_SIGNUP) {
            if (resultCode == RESULT_OK) {

                // TODO: Implement successful signup logic here
                // By default we just finish the Activity and log them in automatically

                if(data!=null){
                    String email=data.getStringExtra("email");
                    String password=data.getStringExtra("password");
                    _emailText.setText(email);
                    _passwordText.setText(password);
                }
                //this.finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        // Disable going back to the MainActivity
        moveTaskToBack(true);
    }

    public void onLoginSuccess() {
        _loginButton.setEnabled(true);
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();

    }

    public void onLoginFailed() {
        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

        _loginButton.setEnabled(true);
    }

    private Thread newThread;         //声明一个子线程
    static Socket client;
    public static volatile boolean valid=true;

    public boolean validate() {


        valid = true;

        String email = _emailText.getText().toString();
        String password = _passwordText.getText().toString();

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            _emailText.setError("enter a valid email address");
            valid = false;
        } else {
            _emailText.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            _passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        if(email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()||password.isEmpty() || password.length() < 4 || password.length() > 10){

        }else{


            newThread=new Thread() {
                @Override
                public void run() {
                    //这里写入子线程需要做的工作
                    String result="";
                    String email=_emailText.getText().toString();
                    String password=_passwordText.getText().toString();
                    try {

                        //client = new Socket("e1868x8452.iok.la", 22329);
                        client = new Socket();
                        SocketAddress socketAddress = new InetSocketAddress("e1868x8452.iok.la", 22329);
                        client.connect(socketAddress,3000);//单位为毫秒

                        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
                        DataInputStream dis = new DataInputStream(client.getInputStream());
                        dos.writeUTF("confirmLogin");
                        dos.flush();
                        dos.writeUTF(email + " " + password);
                        dos.flush();
                        result = dis.readUTF();
                        if (dos != null)
                            dos.close();

                        if (result != null) {
                            switch (result) {
                                case "login":
                                    //formula.setText("login");
                                    //Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                                    //startActivityForResult(intent, 0);
                                    //finish();
                                    //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                                    _emailText.setError(null);
                                    _passwordText.setError(null);
                                    break;
                                case "passwordiswrong":
                                    //_passwordText.setError("enter the true password");  //子线程中修改UI会闪退
                                    valid = false;
                                    break;
                                case "emailnotregist":
                                    //_emailText.setError("email address is not regist");
                                    valid = false;
                                    break;
                                default:
                                    valid = false;
                                    break;
                            }
                        }else{
                            valid = false;

                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                        valid=false;
                    }
                }
            };
            newThread.start();
            try {

                newThread.join();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }//如果子线程没执行完毕数据不会改变
        }
        return valid;
    }





}
